package cn.csust.net2.manager.client.chat;

import java.util.Iterator;
import java.util.List;

import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.shared.po.Message;
import cn.csust.net2.manager.shared.po.Student;
import cn.csust.net2.manager.shared.po.User;
import cn.csust.net2.manager.shared.service.BeanService;
import cn.csust.net2.manager.shared.service.BeanServiceAsync;

import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
/*
 * gwt中的线程类Timer
 * 
 * 此类用于监听数据库时候法向自己的信息
 */
public class MessageListener extends Timer{
	
	BeanServiceAsync<Message> messageService = GWT.create(BeanService.class);
	User user;
	boolean flag = true;
	
	public MessageListener(User user) {
		super();
		this.user = user;
	}

	@Override
	public void run() {
		if(flag){
			Message message = new Message();
			User uuser = new Student();
			uuser.setUserID(user.getUserID());
			message.setReceiver(uuser);
			messageService.findByExample("Message", message, new AsyncCallback<List<Message>>() {
				
				@Override
				public void onSuccess(List<Message> result) {
					// TODO Auto-generated method stub
					if(!result.isEmpty()){
						Info.display("消息提醒", "您有新的消息，请注意查看");
						
						//用来提醒消息到达的声音，还未实现
//						OurMediaPlayer omp = new OurMediaPlayer() ;
//						omp.playMessageComing();
						Message message;
						Iterator<Message> it = result.iterator();
						while(it.hasNext()){
							message = it.next();
							User sender = message.getSender();
							ChatTab currentChatTab = App.getChatPool().showChatTab(sender);
							currentChatTab.getHtmlShower().setHTML(currentChatTab.getChatContent().append(sender.getName() + " : " + message.getMessageContent() +"<br>").toString() );
							App.getChatPool().showChatTab(sender);
							
							
							
							//message发送完之后将其删除
							messageService.delete("Message", message, new AsyncCallback<Void>(){

								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									
								}

								@Override
								public void onSuccess(Void result) {
									// TODO Auto-generated method stub
								}
								
							});
							
						}
					}
				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}
			});


		}
		
	}
	/*
	 * 关闭message监听
	 */
	public void close(){
		flag = false;
	}

	
}
